<template>
  <div class="searchContent">
    <div class="inputBox">
      <!-- 输入框 -->
      <input
        type="text"
        placeholder="搜索歌曲、歌手、专辑"
        v-model="inputGet"
        @click="change(inputVal)"
        ref="inputTip"
      />
      <div class="sea iconfont iconsousuo" @click="searchSong(inputVal)"></div>
      <div class="talk iconfont iconyuyin1"></div>
      <div v-show="bcShow">
        <!-- 搜索辅助 -->
        <div class="bc" @click="searchSong(inputVal)">搜索：{{inputVal}}</div>
        <div
          class="filter"
          v-for="(item, index) in fuzzyFilter"
          :key="index"
          @click="searchSong(item)"
        >
          <div class="iconfont iconsousuo map"></div>
          <div class="text">{{item}}</div>
        </div>
        <!-- 历史记录 -->
        <div class="historyText">历史记录：</div>
        <div class="historyBox">
          <div
            class="history"
            v-for="(item, index) in historyData"
            :key="index"
            @click="searchSong(item)"
          >
            {{item}}
            <span @click.stop="delHistory(index)" class="iconfont iconziyuan"></span>
          </div>
        </div>
      </div>
    </div>
    <!-- 热门搜索 -->
    <div class="hotSearch" v-show="!isShow &&loadingFlag">
      <p>热门搜索：</p>
      <div class="searchContent">
        <span
          v-for="(item, index) in hotSearch"
          :key="index"
          @click="searchSong(item.first)"
        >{{item.first}}</span>
      </div>
    </div>
    <div v-if="!loadingFlag" class="catBox">
      <div class="imgWrap cat">
        <img src="../assets/image/loading.gif" alt />
      </div>
    </div>
    <div></div>
    <!-- 钰婷模块 -->
    <div class="songs-list-box">
      <ul v-show="songShow">
        <li v-for="(item, index) in load.data" :key="index" @click="sendData(item.id,index)">
          <div class="songs-list">
            <div class="songs-list-left">
              <h3>{{item.name}}</h3>
              <span>SQ</span>
              <p v-for="(item2, index2) in item.artists" :key="index2">{{item2.name}}</p>
            </div>
            <div class="songs-list-right">
              <i class="iconfont">&#xe696;</i>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div v-show="tipFlag" class="tipText">搜索不到歌曲，请换个关键字</div>
  </div>
</template>
<style lang="scss">
@import "../assets/scss/search.scss";
</style>

<script>
import { mapState, mapMutations } from "vuex";
import { getHongSong, getSearchSong } from "../assets/api";
export default {
  name: "Search",
  data() {
    return {
      inputVal: "",
      searchMusic: "",
      sulrSearch: [], //模糊搜索结果
      fuzzyFilter: [], //筛选出的5条模糊搜索
      keys: [],
      isShow: false, //热门显示按钮
      bcShow: false, //辅助搜索显示按钮
      songShow: true, //歌单显示按钮
      throttleBut: true, //节流开关
      loadingFlag: false,
      tipFlag: false,
      // 触底加载参数
      load: {
        page: 0,
        data: [],
        canRun: true
      }
    };
  },
  async created() {
    let res = await getHongSong();
    this.getHotMusic(res); //vuex
    this.setHisTen();
    document.addEventListener("keydown", e => {
      if (e.keyCode == 13) {
        this.searchSong(this.inputVal);
      }
    });
  },
  computed: {
    //input值获取
    inputGet: {
      get() {
        return this.inputVal;
      },
      set(newVal) {
        this.inputVal = newVal;
      }
    },
    ...mapState({
      hotSearch: state => state.Search.hotMusic,
      historyData: state => state.Search.historySearch
    })
  },
  watch: {
    //观测输入值
    inputVal: {
      handler: function() {
        var value = this.inputVal;
        value = value.replace(/\s+/g, "");
        this.isShow = false;
        if (value == "") {
          this.isShow = false;
          this.bcShow = false;
        } else {
          this.isShow = true;
          this.bcShow = true;
        }
        this.searchMusic = [];
        if (this.throttleBut) {
          this.throttleBut = false;
          this.searchSlu(this.inputVal);
          setTimeout(() => {
            this.throttleBut = true;
          }, 600);
        }
        this.searchSlu(this.inputVal);
      }
    }
  },
  methods: {
    //歌曲搜索
    async searchSong(value) {
      value = value.replace(/\s+/g, "");
      this.$refs.inputTip.classList.remove("tipStyle");
      this.$refs.inputTip.placeholder = "搜索歌曲、歌手、专辑";
      if (value == "") {
        this.$refs.inputTip.placeholder = "请输入歌曲关键字";
        this.$refs.inputTip.classList.add("tipStyle");
        return;
      }
      this.tipFlag = false;
      this.isShow = true;
      this.bcShow = false;
      let res = await getSearchSong(value);
      this.songShow = true;
      this.searchMusic = res;
      if (this.searchMusic.length == 0) {
        this.tipFlag = true;
      }
      //计算分页(触底加载)
      this.load.canRun = true;
      this.bottomLoadCal();
      //写入记录到本地储存
      localStorage.setItem(`${Date.now()}`, value);
      this.setHisTen();
    },
    //模糊搜索
    async searchSlu(value) {
      this.fuzzyFilter = [];
      value = value.replace(/\s+/g, "");
      if (value == "") return;
      let res = await getSearchSong(value);
      this.sulrSearch = res;
      for (let i = 0; i < this.sulrSearch.length; i++) {
        if (this.fuzzyFilter.length >= 5) {
          break;
        }
        if (this.fuzzyFilter.indexOf(this.sulrSearch[i].name) == -1) {
          this.fuzzyFilter.push(this.sulrSearch[i].name);
        }
      }
    },

    //传递数据到 vuex (热搜歌曲 搜索记录)
    ...mapMutations(["getHotMusic", "setHisTen"]),
    getHotMusic(val) {
      this.$store.commit("getHotMusic", val);
      this.loadingFlag = true;
    },
    //点击清除信息
    change(val) {
      val = val.replace(/\s+/g, "");
      this.$refs.inputTip.classList.remove("tipStyle");
      this.$refs.inputTip.placeholder = "搜索歌曲、歌手、专辑";
      this.tipFlag = false;
      if (val == "") {
        this.isShow = false;
        this.bcShow = false;
        this.songShow = false;
      } else {
        this.isShow = true;
        this.bcShow = true;
        this.songShow = false;
      }
    },
    //获取十条历史信息
    setHisTen() {
      var reg = /^\d+$/;
      let data = [];
      // 键名排序
      // let keys = [];
      this.keys = [];
      var test = new RegExp(reg);
      if (localStorage.length < 10) {
        for (let i = 0; i < localStorage.length; i++) {
          if (test.test(localStorage.key(i))) {
            this.keys.push(Number(localStorage.key(i)));
          }
        }
      } else {
        for (let i = 0; i < localStorage.length; i++) {
          if (test.test(localStorage.key(i))) {
            this.keys.push(Number(localStorage.key(i)));
          }
          // if (keys.length >= 10) break;
        }
      }
      this.keys.sort(function(a, b) {
        return b - a;
      });
      if (this.keys.length < 10) {
        for (let i = 0; i < this.keys.length; i++) {
          data.push(localStorage.getItem(this.keys[i]));
        }
      } else {
        for (let i = 0; i < 10; i++) {
          data.push(localStorage.getItem(this.keys[i]));
        }
      }
      this.$store.commit("setHisTen", data);
    },
    delHistory(num) {
      localStorage.removeItem(this.keys[num]);
      this.setHisTen();
    },
    //触底加载计算
    bottomLoadCal() {
      this.load.page = Math.ceil(this.searchMusic.length / 15.0);
      // console.log(this.load.page, this.searchMusic.length);
      this.load.data = this.searchMusic.slice(0, 15);
      document.addEventListener("scroll", () => {
        // console.log("滚动了");
        
        if (this.load.canRun) {
          this.load.canRun = false;
          if (this.load.page > 1) {
            setTimeout(() => {
              this.load.canRun = true;
              let scrollT =
                document.body.scrollTop || document.documentElement.scrollTop; //滑动的高度
              let winH = window.innerHeight;    //文档显示的高度
              //获取滚动条总长
              let scrollH =
                document.body.scrollHeight ||         //浏览器所有内容的高度
                document.documentElement.scrollHeight;               
              if (((scrollT + winH) / scrollH).toFixed(1) >= 0.9) {
                this.bottomLoadGo();
                this.load.page--;
                // console.log("触底加载了");
              }
            }, 200);
          }
        }
      });
    },
    //加载更多数据
    bottomLoadGo() {
      var middle = this.searchMusic.slice(15, 30);
      // console.log(middle)
      this.load.data = this.load.data.concat(middle);
    },

     sendData(id, idx) {
      var b = [];
      this.searchMusic.forEach((el)=>{
          var data = {
          id: el.id,
          name: el.name,
          artists: artiAdd(el.artists),
          picurl:
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592910584303&di=0d1893709e261a1a71c152a26a9268ad&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20170919%2Fab22e693286747c6a17646104656347e.jpeg",
        };
        b.push(data);
      })
      this.$store.commit("toSongList", b);
      this.$store.commit("songsIdx", idx);
      function artiAdd(arr) {
        var artists = [];
        arr.forEach(item => {
          artists.push(item.name);
        });
        return artists;
      }
    }
  }
};
</script>
